package com.kasax.httpclient.core;

import com.kasax.httpclient.beans.Request;
import com.kasax.httpclient.beans.Response;
import com.kasax.httpclient.core.inters.Call;
import com.kasax.httpclient.core.inters.Interceptor;
import com.kasax.httpclient.utils.LogUtils;

import java.io.IOException;
import java.util.List;

public class RealInterceptorChain implements Interceptor.Chain {
    private final List<Interceptor> interceptors;
    private final int index;
    private final RealCall call;
    private final int connectTimeout;
    private final int callTimeout;
    private final int readTimeout;
    private final int writeTimeout;
    private final HttpConnection connection;
    private Request request;
    private HttpCondec httpCondec = new HttpCondec();

    public RealInterceptorChain(List<Interceptor> interceptors, int index, RealCall realCall, HttpConnection connection) {
        this.interceptors = interceptors;
        this.index = index;
        this.call = realCall;
        this.request = call.request();
        this.connectTimeout = call.client().conenctTimeout;
        this.callTimeout = call.client().callTimeout;
        this.readTimeout = call.client().readTimeout;
        this.writeTimeout = call.client().writeTimeout;
        this.request = call.request();
        this.connection = connection;
    }

    @Override
    public Request request() {
        return request;
    }

    @Override
    public Response procced() throws IOException {
        LogUtils.i(getClass(), "procced index: " + index);
        return procced(connection);
    }

    @Override
    public Response procced(HttpConnection connection) throws IOException {
        LogUtils.i(getClass(), "procced with connection index: " + index);
        // 获取下一个拦截器链
        RealInterceptorChain next = new RealInterceptorChain(interceptors, index + 1, call, connection);
        // 获取当前的拦截器
        Interceptor interceptor = interceptors.get(index);
        Response response = interceptor.intercpt(next);
        return response;
    }


    @Override
    public HttpConnection connection() {
        return connection;
    }

    @Override
    public Call call() {
        return call;
    }

    @Override
    public int connectTimeoutMillis() {
        return connectTimeout;
    }

    @Override
    public int readTimeoutMillis() {
        return readTimeout;
    }

    @Override
    public int writeTimeoutMillis() {
        return writeTimeout;
    }

    @Override
    public int callTimeoutMillis() {
        return callTimeout;
    }

    @Override
    public HttpCondec httpCodec() {
        return httpCondec;
    }
}
